package com.netty.nio.demo2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class ServerChannel {

  public static void main(String[] args) throws IOException {
      ByteBuffer byteBuffer = ByteBuffer.allocate(100);
      ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); //打开通道

      serverSocketChannel.bind(new InetSocketAddress(8082));
      //由于accept方法是阻塞的，我们只需要一行代码就能让它变成非阻塞的
      //开启非阻塞的之后accept方法如果没有连接到客户端就会从阻塞变成返回'null'
      serverSocketChannel.configureBlocking(false);//开启非阻塞
      while (true){
//          System.out.println("waiting...");
          SocketChannel socketChannel = serverSocketChannel.accept(); //阻塞方法

//          System.out.println(socketChannel);

              if(socketChannel!=null){
                  System.out.println("等待读取");
                  socketChannel.configureBlocking(false); //设置SocketChannel为非阻塞
                  int read = socketChannel.read(byteBuffer);//阻塞方法
                  System.out.println("读取到"+read+"字节");
                  if(read>0){

                      byteBuffer.flip();
                      System.out.println(StandardCharsets.UTF_8.decode(byteBuffer).toString());
                  }

              }

      }
  }
}
